<template>
  <ContentWrap>

    <el-tabs v-model="activeName" class="demo-tab" @tab-change="tabClickHandle">
      <el-tab-pane label="待打款" name="0" />
      <el-tab-pane label="已打款" name="1" />
      <el-tab-pane label="全部" name="" />
    </el-tabs>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-25px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="90px">
      <el-form-item label="提现批次号" prop="withdrawBatchNo">
        <el-input v-model="queryParams.withdrawBatchNo" placeholder="请输入提现批次号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker v-model="queryParams.applyTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
      <el-form-item label="打款时间" prop="paymentTime">
        <el-date-picker v-model="queryParams.paymentTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
      <el-form-item label="打款状态" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择打款状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.WPAYMENT_STATUS_TYPE)" :value="dict.value"
            :label="dict.label" :key="dict.value" />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="审核状态" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择打款状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.WPAYMENT_STATUS_TYPE)" :value="dict.value"
            :label="dict.label" :key="dict.value" />
        </el-select>
      </el-form-item>
      -->

      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 查询
        </el-button>
        <el-button type="primary" @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 财务看板 -->
  <ContentWrap>
    <div class="financial-dashboard">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="dashboard-card">
            <template #header>
              <div class="dashboard-title">财务看板</div>
            </template>
            <el-row :gutter="15">
              <!-- 待打款订单 -->
              <el-col :span="6">
                <div class="dashboard-content">
                  <div class="dashboard-title">待打款订单</div>
                  <div class="dashboard-value">{{ dashboardData.waitingPayOrderCount || 0 }}</div>
                </div>
              </el-col>

              <!-- 待打款金额 -->
              <el-col :span="6">
                <div class="dashboard-content">
                  <div class="dashboard-title">待打款金额</div>
                  <div class="dashboard-value">¥{{ dashboardData.waitingPayAmount || 0 }}</div>
                </div>
              </el-col>

              <!-- 已打款订单 -->
              <el-col :span="6">
                <div class="dashboard-content">
                  <div class="dashboard-title">已打款订单</div>
                  <div class="dashboard-value">{{ dashboardData.payCount || 0 }}</div>
                </div>
              </el-col>

              <!-- 已打款金额 -->
              <el-col :span="6">
                <div class="dashboard-content">
                  <div class="dashboard-title">已打款金额</div>
                  <div class="dashboard-value">¥{{ dashboardData.payAmount || 0 }}</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </ContentWrap>
  <ContentWrap>
    <!-- 批量信息展示 -->
    <div class="batch-info">
      <el-row :gutter="10">
        <el-col :span="1.6">
          <el-button type="primary" @click="handleBatchPass">
            批量通过
          </el-button>
        </el-col>
        <el-col :span="1.6">
          <el-button type="primary" @click="handleBatchReject">
            批量驳回
          </el-button>
        </el-col>
        <el-col :span="1.6">
          已选择{{ selectedOrders.length || 0 }}笔，
          总计结算金额: ￥{{ formatMoney(totalSettleAmount) || 0 }},
        </el-col>
      </el-row>
    </div>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange" :table-layout="auto">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
      <el-table-column label="提现批次号" align="center" prop="withdrawBatchNo">
        <!--使用slot-->
        <template #default="scope">
          <el-button link type="primary" @click="openDetail(scope.row.withdrawBatchNo)">
            {{ scope.row.withdrawBatchNo }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="提现金额" align="center" prop="withdrawAmount" />
      <el-table-column label="订单笔数" align="center" prop="orderCount" />
      <el-table-column label="申请时间" align="center" prop="applyTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="打款时间" align="center" prop="paymentTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="打款状态" align="center" prop="paymentStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.WPAYMENT_STATUS_TYPE" :value="scope.row.paymentStatus" />
        </template>
      </el-table-column>
      <el-table-column label="已打款金额" align="center" prop="paidAmount" />
        
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HAUDIT_STATUS_TYPE" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.auditStatus === 0"
            v-hasPermi="['hotel:order-withdrawal-summary:passHandler']" @click="tgHandle(scope.row.id)">
            通过
          </el-button>
          <el-button link type="primary" v-if="scope.row.auditStatus === 0"
            v-hasPermi="['hotel:order-withdrawal-summary:rejectHandler']" @click="rejectHandle(scope.row.id)">
            驳回
          </el-button>
          <el-button link type="primary" v-if="scope.row.auditStatus === 1 && scope.row.paymentStatus === 0"
            v-hasPermi="['hotel:order-withdrawal-summary:dkHandler']" @click="openPayForm(scope.row.id)">
            打款
          </el-button>
          <ReceiptViewer
          v-if="scope.row.paymentStatus === 2"
          :url="scope.row.hdUrl"
          title="查看电子回单"
        />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 
  <OrderWithdrawalSummaryForm ref="formRef" @success="getList" /> -->
  <OrderWithdrawalSummaryDetail ref="detailRef" @success="getList" />
  <PayForm ref="payFormRef" @success="getList"/>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as OrderWithdrawalSummaryApi from '@/api/hotel/orderwithdrawalsummary'
import OrderWithdrawalSummaryDetail from './OrderWithdrawalSummaryDetail.vue'
import ReceiptViewer from './ReceiptViewer.vue'
import PayForm from './payform.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { tr } from 'element-plus/es/locale'
defineOptions({ name: 'OrderWithdrawalSummary' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  withdrawBatchNo: undefined,
  withdrawAmount: undefined,
  orderCount: undefined,
  applyTime: [],
  paymentTime: [],
  paymentStatus: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderWithdrawalSummaryApi.getOrderWithdrawalSummaryPage(queryParams)
    list.value = data.list
    total.value = data.total
    getDashboardData();
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderWithdrawalSummaryApi.deleteOrderWithdrawalSummary(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 todo*/
const handleExportDetail = async (id: number) => {
  try {
    // 导出的二次确认
    await message.exportConfirm("确定导出酒店收款-订单提现.xls")
    // 发起导出
    exportLoading.value = true
    const data = await OrderWithdrawalSummaryApi.handleExportDetail(id)
    download.excel(data, '酒店收款-订单提现.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/**
 * todo 下载回执
 * @param id 
 */
const handleExportHd = async (id: number) => {
  try {
    await message.exportConfirm("确定要导出回单？");
    exportLoading.value = true;
    const resp = await OrderWithdrawalSummaryApi.handleExportHd(id);
    // 返回url 弹窗并可以下载图片
    ElMessageBox({
      title: '图片导出成功',
      message: h('img', {
        src: resp.imageUrl,
        style: 'max-width: 100%; max-height: 400px; margin: 10px 0;'
      }),
      showCancelButton: true,
      confirmButtonText: '下载',
      cancelButtonText: '关闭',
      dangerouslyUseHTMLString: true,
    }).then(() => {
      // 用户点击“下载”
      const link = document.createElement('a');
      link.href = resp.imageUrl;
      link.download = `withdrawal_${id}.jpg`;
      link.click();
    });
  } catch (e: any) {
    console.log("业务回单下载异常".concat(e.message));
  } finally {
    exportLoading.value = false;
  }
}
/** 初始化 **/
onMounted(() => {
  getList();
})


const activeName = ref('')
const tabClickHandle = (tabName: string) => {
  if (tabName === "all") {
    queryParams.paymentStatus = undefined;
  } else {
    queryParams.paymentStatus = Number(tabName);
  }
  //queryParams.withdrawStatus = tabName === 'all' ? undefined :Number(tabName);
  handleQuery();
}

const dashboardData = ref<any>({})

const getDashboardData = async () => {
  try {
    const data = await OrderWithdrawalSummaryApi.getFinancialDashboard()
    dashboardData.value = data
  } catch (error) {
    console.error('获取财务看板数据失败:', error)
  }
}
const detailRef = ref();
const openDetail = async (withdrawBatchNo: string) => {
  detailRef.value.open(withdrawBatchNo)
}
const payFormRef =ref();
const openPayForm =async (id:number) =>{
  payFormRef.value.open(id)
}

const tgHandle = async (id: number) => {
  await message.confirm("确定要通过该提现操作吗?");
  try {
    const res = await OrderWithdrawalSummaryApi.tgHandle(id);
    if (res) {
      message.success("该提现审核已成功提交");
    } else {
      message.success("该提现提交失败，请稍后再试");
    }
    getList();
  } catch (msg: any) {
    console.log("操作异常，错误信息".concat(msg));
    getList();

  }
}
 

//驳回操作
const rejectHandle = async (id: number) => {
  let rejectReason = '';

  try {
    // 使用原生 textarea
    const result = await ElMessageBox({
      title: '驳回原因',
      message: h('div', [
        h('p', { style: 'margin-bottom: 10px; color: #606266;' }, '请输入驳回原因：'),
        h('textarea', {
          style: 'width: 100%; height: 50px; padding: 5px; border: 1px solid #dcdfe6; border-radius: 4px;',
          placeholder: '请输入驳回原因，最多200个字符',
          maxlength: 200,
          onInput: (e) => {
            rejectReason = e.target.value;
          },
          onKeyup: (e) => {
            if (e.target.value.length > 200) {
              e.target.value = e.target.value.substring(0, 200);
              rejectReason = e.target.value;
            }
          }
        }),
        h('div', { style: 'margin-top: 5px; font-size: 12px; color: #909399; text-align: right;' },
          () => `${rejectReason.length}/200`)
      ]),
      showCancelButton: true,
      confirmButtonText: '确认驳回',
      cancelButtonText: '取消',
      dangerouslyUseHTMLString: true,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          if (!rejectReason.trim()) {
            ElMessage.warning('请输入驳回原因');
            return false;
          }
          if (rejectReason.length > 500) {
            ElMessage.warning('驳回原因不能超过200个字符');
            return false;
          }
        }
        done();
      }
    });

    if (result === 'confirm') {
      const rejectRes = await OrderWithdrawalSummaryApi.rejectHandler(id, rejectReason);
      console.log('驳回返回:', rejectRes);
      if (rejectRes) {
        message.success("该提现审核已成功驳回");
        getList();
      } else {
        message.success("该提现审核驳回失败，请稍后再试");
        getList();
      }
    }
  } catch (msg: any) {
    getList();
    console.log("提现审核驳回操作异常，错误信息".concat(msg));
  }
}
const formatMoney = (value: number): string => {
  return Number(value || 0).toFixed(2)
}

const selectedOrders = ref<any[]>([])
const handleSelectionChange = (selection: any[]) => {
  selectedOrders.value = selection
}

const totalSettleAmount = computed(() => {
  return selectedOrders.value.reduce((sum, item) => sum + item.withdrawAmount, 0)
})

const handleBatchPass = async () => {
  if (selectedOrders.value.length === 0) return;
  const ids = selectedOrders.value.map(o => o.id);
  const statusCount: number = selectedOrders.value.map(m => m.auditStatus).filter(s => s !== 0 || s !== undefined).length;
  if (statusCount > 0) {
    message.alertError("请选择状态为 待审核 的数据进行批量通过");
    return;
  }
  ElMessageBox.confirm('确认对 ${selectedOrders.value.length} 笔进行批量通过吗?', '提示')
    .then(async () => {
      const res: boolean = await OrderWithdrawalSummaryApi.handleBatchPass(ids);
      if (res) {
        message.success('批量通过提交成功')
        // 成功后刷新列表
        await getList();
      } else {
        message.error('批量通过提交失败，请稍后再试')
      }
      selectedOrders.value = []
    }).catch((msg: any) => {
      message.info('批量通过异常')
    })
}
const handleBatchReject = async () => {
  if (selectedOrders.value.length === 0) return;
  const ids = selectedOrders.value.map(o => o.id);
  const statusCount: number = selectedOrders.value.map(m => m.auditStatus).filter(s => s !== 0 || s !== undefined).length;
  if (statusCount > 0) {
    message.alertError("请选择状态为 待审核 的数据进行批量驳回");
    return;
  }
  ElMessageBox.confirm('确认对 ${selectedOrders.value.length} 笔进行批量驳回吗?', '提示')
    .then(async () => {
      const res: boolean = await OrderWithdrawalSummaryApi.handleBatchReject(ids);
      if (res) {
        message.success('批量驳回提交成功')
        // 成功后刷新列表
        await getList();
      } else {
        message.error('批量驳回提交失败，请稍后再试')
      }
      selectedOrders.value = []
    }).catch((msg: any) => {
      message.info('批量驳回异常')
    })
}
</script>

<style lang="css">
.dashboard-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.dashboard-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.dashboard-content {
  text-align: center;
  padding: 14px;
}

.dashboard-value {
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
  margin-top: 5px;
}

.detail-row {
  font-size: 14px;
  margin-bottom: 8px;
  white-space: nowrap;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
}
</style>